package com.three.utils;

import com.three.common.message.base.BaseMessage;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Created by Mathua on 2017/6/27.
 */
public final class ObjectUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ObjectUtils.class);

    /**
     * 对象转Byte数组
     * @param obj
     * @return
     */
    public static byte[] toBytes(Object obj) {
        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(stream);
            out.writeObject(obj);
            out.flush();
            byte[] bytes = stream.toByteArray();
            LOGGER.debug(bytes.toString());
            return bytes;
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }

    /**
     * 字节数组转对象
     * @param bytes
     * @return
     */
    public static <T extends Object> T toT(byte[] bytes) {
        try {
            LOGGER.debug(bytes.toString());
            ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
            ObjectInputStream in = new ObjectInputStream(stream);
            return (T) in.readObject();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }

}
